//
//  HNProofIdentityController.m
//  JHFBaseProject
//
//  Created by 朱传正 on 2017/1/4.
//  Copyright © 2017年 好牛. All rights reserved.
//

#import "HNProofIdentityController.h"

@interface HNProofIdentityController ()<UINavigationControllerDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate>

@property (nonatomic,retain) UIImagePickerController * imagePicker;

@property (nonatomic,strong) UIImageView *imageView;
@property (nonatomic,strong) NSString *imageStr;

@end

@implementation HNProofIdentityController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (IBAction)backAction:(UIButton *)sender {
      [self.navigationController popViewControllerAnimated:YES];
}


- (IBAction)inputImage:(UIButton *)sender {
    
    [self updateUserImage];
}



- (IBAction)nextAction:(UIButton *)sender {
    
    [self registerUserInfo];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

#pragma mark -  上传头像
-(void)updateUserImage{
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        dispatch_async(dispatch_get_main_queue(),^{
            UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"更换头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册选择", @"拍照", nil];
            actionSheet.delegate = self;
            actionSheet.tag = 1001;
            [actionSheet showInView:self.view];
            self.imagePicker = [[UIImagePickerController alloc]init];
            self.imagePicker.delegate = self;
            self.imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
            self.imagePicker.allowsEditing = YES;
        });
    });
}

#pragma mark - 判断设备是否有摄像头
- (BOOL) isCameraAvailable
{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}
#pragma mark - UIActionSheet delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag==1001) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.editing = YES;
        _imagePicker.allowsEditing = YES;
        _imagePicker.delegate = self;
        if (buttonIndex == 0)
        {
            //相册
            _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //[self presentModalViewController:_imagePicker animated:YES];
            [self presentViewController:_imagePicker animated:YES completion:nil];
            
        }else if (buttonIndex == 1){
            //照相机
            if ([self isCameraAvailable]) {
                _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                //[self presentModalViewController:_imagePicker animated:YES];
                [self presentViewController:_imagePicker animated:YES completion:nil];
            }else{
                [self showHint:@"该设备没有摄像头"];
            }
        }else
        {
            //取消
        }
    }
    
}
#pragma mark - UIImagePicker delegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //[picker dismissModalViewControllerAnimated:YES];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    //UIImage *image = [[info objectForKey:UIImagePickerControllerEditedImage] retain];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    
    
    [self performSelector:@selector(saveImage:) withObject:image afterDelay:0];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    //    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent];
    //[picker dismissModalViewControllerAnimated:YES];
    //保持状态栏颜色---为黑色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//上传图片
-(void)saveImage:(UIImage *)image{
    NSLog(@"image = %@",image);
    [_flag2 setImage:image forState:UIControlStateNormal];
    
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:url_update_userInfo_image parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        //压缩图片
        __block UIImage * changeImage = [self compressImage:image toTargetWidth:333];
        
        NSData *data = UIImagePNGRepresentation(changeImage);
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //打印下上传进度
        NSLog(@"上传进度");
        NSLog(@"%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //上传成功
        NSLog(@"上传成功");
        NSError *error;
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        
        NSLog(@"%@",data);
        
        
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            return;
        }
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        
        
        if ([result isEqualToString:@"1"]) {
            _imageStr = [NSString stringWithFormat:@"%@",[data objectForKey:@"obj"]];
            NSLog(@"------obj = %@",_imageStr);
            
            NSString *imageStr = [NSString stringWithFormat:@"%@%@",url_Base,_imageStr];
            [_flag2.imageView sd_setImageWithURL:[NSURL URLWithString:imageStr] placeholderImage:[UIImage imageNamed:@"2.png"]];
            
          
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                HNLoginViewController *loginVC = [[HNLoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //上传失败
        NSLog(@"上传失败");
        NSLog(@"%@",error.description);
    }];
    
}

//压缩图片
- (UIImage *)compressImage:(UIImage *)sourceImage toTargetWidth:(CGFloat)targetWidth {
    CGSize imageSize = sourceImage.size;
    
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    
    NSLog(@"width = %f,height = %f",width,height);
    
    CGFloat targetHeight = (targetWidth / width) * height;
    NSLog(@"targetWidth = %f targetHeight = %f",targetWidth,targetHeight);
    
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [sourceImage drawInRect:CGRectMake(0, 0, targetWidth, targetHeight)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}


-(void)registerUserInfo{
    
    [NSThread sleepForTimeInterval:0.5];
    
    if (_imageStr.length == 0) {
        [self showHint:@"请导入医生职业证书"];
        return;
    }

     NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:_username,@"username",_password,@"password",nil];
    
    [param setObject:_captcha forKey:@"captcha"];
    
    [param setObject:_realName forKey:@"realName"];
    [param setObject:_hospitalId forKey:@"hospitalId"];
    [param setObject:_departmentId forKey:@"departmentId"];
    [param setObject:_professionalTitleId forKey:@"professionalTitleId"];
    [param setObject:_telephone forKey:@"telephone"];
    [param setObject:_flag1 forKey:@"flag1"];
    [param setObject:_flag2 forKey:@"flag2"];
    [param setObject:_imageStr forKey:@"imageStr"];
    
    [param setObject:@"1" forKey:@"isDoctor"];
    
        NSLog(@"param = %@",param);
        
        
        AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager POST:url_Register parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSError * error;
            NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
            [self hideHud];
            if (error) {
                NSLog(@"====error1:%@",error);
                [self showHint:@"注册失败"];
                return;
            }
            NSLog(@"==dict:%@",data);
            NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
            if ([result isEqualToString:@"1"]) {
                NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"obj"]];
                
                //回到登录页
                int index=(int)[[self.navigationController viewControllers]indexOfObject:self];
                [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:index-3]animated:YES];
                
                NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
                if ([info isEqualToString:msg_InvalidLoginInformation]) {
                    
                    [AppConfig removeUserInfo];
                    
                    [[EMClient sharedClient] logout:YES];
                    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                    
                    HNLoginViewController *loginVC = [[HNLoginViewController alloc]init];
                    
                    [self.navigationController pushViewController:loginVC animated:YES];
                }
                [self showHint:info];
            }else{
                NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
                if ([info isEqualToString:msg_InvalidLoginInformation]) {
                    
                    [AppConfig removeUserInfo];
                    
                    [[EMClient sharedClient] logout:YES];
                    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                    
                    HNLoginViewController *loginVC = [[HNLoginViewController alloc]init];
                    
                    [self.navigationController pushViewController:loginVC animated:YES];
                }
                [self showHint:info];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull   error) {
            NSLog(@"====error:%@",error);
            [self hideHud];
            [self showHint:@"注册失败"];
        }];

    
    
}

@end
